package com.example.service.impl;

import com.example.Repository.CommentRepository;
import com.example.domain.Blog;
import com.example.domain.property.Comment;
import com.example.service.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.beans.Transient;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentRepository commentRepository;

    //根据文章id查找评论
    @Override
    @Transactional  //在方法上面添加事务，使得session等到该方法执行结束后才失效
    public List<Comment> findAllByBlogId(Long blogId) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "createTime");   //DESC降序
        Sort sort = Sort.by(order);
        List<Comment> comments = commentRepository.findAllByBlogId(blogId);  //所有的评论
        for (Comment comment: comments) {
            List<Comment> replyList = comment.getReplyList();
            List<Comment> tempList=new ArrayList<>();   //放置一个评论所有的子评论
            for (Comment c : replyList) {   //遍历第一层子评论
                eachComment(tempList,c);    //将子评论以下所有评论和第一层子评论放在一起
            }
            comment.setReplyList(tempList);  //将所有的子评论赋给
        }
        List<Comment> rootList=new ArrayList<>();   //父评论
        for (Comment comment : comments) {
            if(comment.getParent()==null){
                rootList.add(comment);
            }
        }
        return rootList;
    }
    //添加评论
    @Override
    public Boolean saveComment(Comment comment) {
        Comment c = commentRepository.save(comment);
        if(c!=null){
            return true;
        }
        return false;
    }
    //
    @Override
    @Transactional
    public void eachComment(List<Comment> tempList,Comment comment) {
        tempList.add(comment);
        if(comment.getReplyList().size()>0){
            for (Comment reply : comment.getReplyList()) {
                tempList.add(reply);
                if(reply.getReplyList().size()>0){
                    eachComment(tempList,reply);
                }
            }
        }
    }
}
